<template>
    <div class="user-container">
        <div class="option-box">
            <!-- 面包屑导航 -->
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>用户</el-breadcrumb-item>
                <el-breadcrumb-item>用户列表</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <!-- 添加和批量删除模块 -->
        <el-button-group>
            <el-button type="primary" @Click="gotoAddUser"><el-icon>
                    <CirclePlusFilled />
                </el-icon>添加用户</el-button>
            <el-button type="danger" @click="BatchDeleteUser"><el-icon>
                    <RemoveFilled />
                </el-icon>批量删除</el-button>
        </el-button-group>
        <!-- 数据 -->
        <el-table :data="data.tableData" style="width: 100%" border lazy stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" />
            <el-table-column fixed prop="id" label="id" width="80" align="center" />
            <el-table-column prop="username" label="用户名" align="center" width="120" />
            <el-table-column prop="nickName" label="昵称" width="120" />
            <el-table-column prop="realName" label="真实姓名" width="120" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="phone" label="电话" width="170" />
            <el-table-column prop="address" label="地址" />
            <el-table-column prop="roleId" label="身份" width="80" align="center" />

            <el-table-column label="操作单行" width="120" align="center">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="editUsers(scope.row)">编辑</el-button>
                    <!-- 弹出框 -->
                    <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" :icon="Message"
                        icon-color="#626AEF" title="确定要删除该行用户吗？" @confirm="pretendDelete(scope.row.id)">
                        <template #reference>
                            <el-button link type="danger" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <el-pagination v-model:current-page="data.pageInfo.pageCurrent" v-model:page-size="data.pageInfo.pageSize"
            :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="data.pageInfo.total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />


        <!-- 编辑用户对话框 -->
        <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" v-model="isShowEditDialog" title="编辑用户"
            width="30%" :before-close="handleEdurDiglogClose">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" class="data-form" status-icon>
                <el-form-item label="id" prop="id">
                    <el-input v-model="ruleForm.id" disabled />
                </el-form-item>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="ruleForm.username" />
                </el-form-item>
                <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="ruleForm.nickName" />
                </el-form-item>
                <el-form-item label="真实姓名" prop="realName">
                    <el-input v-model="ruleForm.realName" />
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="ruleForm.phone" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="ruleForm.email" />
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="ruleForm.address" />
                </el-form-item>
                <el-form-item label="角色信息" prop="roleId">
                    <el-select v-model="ruleForm.roleId" placeholder="请选择权限" @click="getRoleInputValue">
                        <el-option v-for="item in roleInputValue" :label="item.roleDesc" :value="item.roleId" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

    </div>
</template>
    
<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue';
import { deleteUserById, getUserListByPage, editUser, pretendDeleteUser } from '@/api/UserApi';
import { getAllRole } from '@/api/RoleApi';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Message } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';

// 路由跳转
const router = useRouter();

// 生命周期
onMounted(() => {
    getUserList(data.pageInfo.pageCurrent, data.pageInfo.pageSize);
})

// ***************************************编辑用户*************************************
const isShowEditDialog = ref(false);
/**
 * 关闭前的回调，会暂停 Dialog 的关闭. 
 * 回调函数内执行 done 参数方法的时候才是真正关闭对话框的时候.
 * @param done 
 */
const handleEdurDiglogClose = (done: () => void) => {
    ElMessageBox.confirm('确定放弃编辑当前列用户吗？')
        .then(() => {
            done()
        })
        .catch(() => {
            // catch error
        })
}

// 点击编辑按钮触发的事件
const editUsers = (user: any) => {
    ruleForm = user;
    isShowEditDialog.value = true

}
// 编辑表单数据
let ruleForm = reactive({
    id: 0,
    username: "",
    nickName: "",
    realName: "",
    phone: "",
    email: "",
    address: "",
    roleId: "",
})

/**
 * 表单验证规则
 */
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 30, message: '账号必须大于8字符，小于30字符！', trigger: 'blur' },
    ],
    nickName: [
        { required: true, message: '请输入用户昵称', trigger: 'blur' },
        { min: 3, max: 30, message: '昵称必须大于3字符，小于30字符！', trigger: 'blur' },
    ],
    realName: [
        { required: true, message: '请输入用户真实姓名', trigger: 'blur' },
        { min: 2, max: 30, message: '姓名必须大于2字符，小于30字符！', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
    ],
    address: [
        { required: true, message: '请输入用户地址', trigger: 'blur' },
        { min: 3, max: 30, message: '名称必须大于5字符，小于255字符！', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/, message: '邮箱格式不正确', trigger: 'blur' }
    ],
    roleId: [
        {
            required: true,
            message: '请至少选择一个角色',
            trigger: 'change',
        },
    ]
})

// ref值
const ruleFormRef = ref<FormInstance>()

/**
 * 提交表单信息
 * @param formEl 
 */
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return // 如果传入的数据为空,直接返回,不执行接下来的操作
    // 验证正则
    await formEl.validate((valid, fields) => {
        if (valid) {
            editUser(ruleForm).then(res => {
                if (res.code == 200) {
                    ElMessage({
                        message: res.msg,
                        type: 'success'
                    })
                    // 清空表数据
                    ruleForm = {
                        id: 0,
                        username: "",
                        nickName: "",
                        realName: "",
                        phone: "",
                        email: "",
                        address: "",
                        roleId: "",
                    }
                    isShowEditDialog.value = false
                } else {
                    ElMessage({
                        message: res.msg,
                        type: 'success'
                    })
                }
            })

        } else {
            ElMessage({
                message: "请按照要求完成信息的填写!",
                type: 'error'
            })
        }
    })
}


// 权限数据存放地址
let roleInputValue: any = ref([]);

// 获取权限下拉框的数据
const getRoleInputValue = async () => {
    await getAllRole().then(res => {
        roleInputValue.value = res.data;
    })
}
//**********************************删除当前列用户******************************* */
const pretendDelete = async (userId: number) => {
    await pretendDeleteUser(userId).then(res => {
        if (res.code == 200) {
            ElMessage({
                message: res.msg,
                type: 'success'
            })
            getUserList(data.pageInfo.pageCurrent, data.pageInfo.pageSize);
        } else {
            ElMessage({
                message: res.msg,
                type: 'error'
            })
        }
    })
}


// ********************************动态数据中心************************************
const data = reactive({
    tableData: [], // 表格数据
    pageInfo: {
        pageCurrent: 1,
        pageSize: 5,
        total: 0
    },
    BatchDeleteIdArray: {},
})

// *****************************************分页获取数据********************************************

/**
 * 分页获取权限信息
 * @param current 
 * @param size 
 */
const getUserList = async (current: Number, size: Number) => {
    await getUserListByPage(current, size).then(res => {
        data.tableData = res.data.records;

        data.pageInfo.pageCurrent = res.data.current;
        data.pageInfo.pageSize = res.data.size;
        data.pageInfo.total = res.data.total;

    })
}

/**
 * 改变PageSize
 * @param val 
 */
const handleSizeChange = (val: number) => {
    data.pageInfo.pageSize = val;
    getUserList(data.pageInfo.pageCurrent, data.pageInfo.pageSize);
}

/**
 * 改变pageCurrent
 * @param val 
 */
const handleCurrentChange = (val: number) => {
    data.pageInfo.pageCurrent = val;
    getUserList(data.pageInfo.pageCurrent, data.pageInfo.pageSize);
}


/***********************************************跳转页面************************************** */
/**
 * 前往添加用户页面
 */
const gotoAddUser = () => {
    router.push('/user/add')
}


/********************************批量删除按钮********************************** */

/**
 * 批量根据id删除用户
 */
const BatchDeleteUser = async () => {
    const obj: any = data.BatchDeleteIdArray;

    // 判断需要批量删除的对象是否为空,为空直接跳出方法
    if (JSON.stringify(obj) == "{}") {
        ElMessage({
            message: "请先选择需要批量删除的权限!",
            type: 'warning'
        })
        return
    }

    let flag = true;
    let msg = "";

    console.log(data.BatchDeleteIdArray);
    // 遍历多选到的选项
    for (const item in obj) {
        await pretendDeleteUser(obj[item]).then(res => {
            if (res.code == 200) {
                msg = res.msg;
                data.BatchDeleteIdArray = {}
                getUserList(data.pageInfo.pageCurrent, data.pageInfo.pageSize);
            } else {
                flag = false;
                msg = res.msg;
            }
        })
    }
    // 添加定时器,延迟播报
    setTimeout(() => {
        if (flag) {
            ElMessage({
                message: msg,
                type: 'success'
            })
        } else {
            ElMessage({
                message: msg,
                type: 'error'
            })
        }
    }, 100);
}

/**
 * 获取批量删除需要的数据
 * @param val 
 */
const handleSelectionChange = (val: any) => {
    const array: Number[] = []
    val.forEach((item: any) => {
        array.push(item.id);
    })

    data.BatchDeleteIdArray = array;
}

</script>
    
<style lang="less" scoped>
.option-box {
    margin: 5px 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

// 数据表
.el-table {
    margin: 10px 0;
}


// 分页
.el-pagination {
    position: absolute;
    right: 30px;
}

.button-group {
    margin-top: 20px;
}
</style>